package com.kye.express.business.networkpoint_query;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.databinding.ActivityNetworkpointMapBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.networkpoint_query.ResultQueryWorkNet;

import java.util.ArrayList;

import io.reactivex.functions.Consumer;

/**
 * 网点查询地图页面
 */
public class NetworkPointMapActivity extends BaseToolbarActivity implements NetworkPointMapActivityContract.NetworkPointMapView {
    private static final String PARAM_DATA = "data";
    private ActivityNetworkpointMapBinding mBinding;
    private BaiduMap mBaiduMap;
    private ArrayList<Marker> mMarkers;

    private int[] mMarkerResourceIds = new int[]{
            R.drawable.icon_place_a,
            R.drawable.icon_place_b,
            R.drawable.icon_place_c,
            R.drawable.icon_place_b,
            R.drawable.icon_place_e,
            R.drawable.icon_place_f,
            R.drawable.icon_place_g,
            R.drawable.icon_place_h,
            R.drawable.icon_place_i,
            R.drawable.icon_place_j,
            R.drawable.icon_place_k,
            R.drawable.icon_place_l,
            R.drawable.icon_place_m,
            R.drawable.icon_place_n,
            R.drawable.icon_place_o,
            R.drawable.icon_place_p,
            R.drawable.icon_place_q,
            R.drawable.icon_place_r,
            R.drawable.icon_place_s,
            R.drawable.icon_place_f,
            R.drawable.icon_place_u,
            R.drawable.icon_place_v,
            R.drawable.icon_place_w,
            R.drawable.icon_place_x,
            R.drawable.icon_place_y,
            R.drawable.icon_place_z
    };

    public static void startActivity(Context context, ArrayList<ResultQueryWorkNet> resultQueryWorkNet) {
        Intent intent = new Intent(context, NetworkPointMapActivity.class);
        intent.putExtra(PARAM_DATA, resultQueryWorkNet);
        context.startActivity(intent);
    }

    private NetworkPointMapActivityContract.NetworkPointMapViewPresenter mPresenter;
    private Dialog mDialog;
    private ArrayList<ResultQueryWorkNet> mDatas;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_networkpoint_map);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        mPresenter = new NetworkPointMapActivityContract.NetworkPointMapViewPresenter(this);
        mPresenter.bind(this);
        setTitle(getString(R.string.networkpoint_query_map_view));
        initView();
        initEvent();
    }

    private void initView() {
        mBaiduMap = mBinding.bmapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomTo(14.0f);
        mBaiduMap.setMapStatus(mapStatusUpdate);
        mMarkers = new ArrayList<Marker>();

        mDatas = (ArrayList<ResultQueryWorkNet>) getIntent().getSerializableExtra(PARAM_DATA);
        if (mDatas != null && mDatas.size() > 0) {
            setupViewByDatas();
        }
    }

    private void setupViewByDatas() {
        ResultQueryWorkNet resultQueryWorkNet = mDatas.get(0);
        if (resultQueryWorkNet != null) {
            LatLng latLng = new LatLng(resultQueryWorkNet.getLnglaty(), resultQueryWorkNet.getLnglatx());
            navigateTo(latLng);
        }
        initMarker();
    }

    public void initMarker() {
        try {
            for (int i = 0; i < mDatas.size(); i++) {
                ResultQueryWorkNet resultQueryWorkNet = mDatas.get(i);
                Marker marker = addMarks(resultQueryWorkNet.getLnglaty(), resultQueryWorkNet.getLnglatx(), 1, i + "", null);
                mMarkers.add(marker);
            }
            if (mMarkers.size() > 0) {
                addMarkPopupView(mMarkers.get(0), mDatas.get(0).getPointName(), mDatas.get(0).getPointAddress(), mDatas.get(0).getLnglaty(), mDatas.get(0).getLnglatx(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Marker addMarks(double lat, double lng, int animationType,
                           String title, BaiduMap.OnMarkerClickListener onMarkerClickListenner) {
        Bitmap bm = null;
//        try {
//            int index = Integer.parseInt(title);
//            if (index >= 0 && index <= mMarkerResourceIds.length - 1) {
//                bm = BitmapFactory.decodeResource(getResources(), mMarkerResourceIds[index]);
//            } else {
//                bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon_point2);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon_point2);
//        }

        VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(getResources(), R.drawable.icon_place_a, null);
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawableCompat.getIntrinsicWidth(),
                vectorDrawableCompat.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawableCompat.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawableCompat.draw(canvas);

        BitmapDescriptor bdA = BitmapDescriptorFactory.fromBitmap(bitmap);
        // 初始化覆盖物位置 及配置信息
        LatLng llA = new LatLng(lat, lng);
        MarkerOptions ooA = new MarkerOptions().position(llA).icon(bdA)
                .zIndex(9).draggable(false);
        // 设置覆盖物出现动画
        if (animationType == 0) {
            ooA.animateType(MarkerOptions.MarkerAnimateType.none);
        } else if (animationType == 1) {
            ooA.animateType(MarkerOptions.MarkerAnimateType.drop);
        } else {
            ooA.animateType(MarkerOptions.MarkerAnimateType.grow);
        }
        // 添加图标到地图中展示
        Marker mMarker = (Marker) (mBaiduMap.addOverlay(ooA));
        mMarker.setTitle(title);
        // 设置覆盖物点击事件监听
        if (onMarkerClickListenner != null) {
            mBaiduMap.setOnMarkerClickListener(onMarkerClickListenner);
        }
        return mMarker;
    }

    public void addMarkPopupView(Marker mMarker, final String title, final String content, final double lat,
                                 final double lng, InfoWindow.OnInfoWindowClickListener listener) {
        initPopupView(mMarker, title, content, lat, lng,
                new InfoWindow.OnInfoWindowClickListener() {

                    @Override
                    public void onInfoWindowClick() {

                    }
                });
    }

    public void initPopupView(Marker mMarker, String title, String content, double lat, double lng,
                              InfoWindow.OnInfoWindowClickListener listener) {
        //linearlayout
        LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setBackgroundResource(R.drawable.popup);
        params.width = ScreenUtils.getScreenWidth() / 100 * 80;
        linearLayout.setLayoutParams(params);
        //textview
        TextView titleText = new TextView(this);
        titleText.setText(title);
        titleText.setGravity(Gravity.CENTER);
        titleText.setTextColor(getResources().getColor(R.color.mapview_popup_title_color));
        //button
        TextView contentText = new TextView(this);
        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        contentParams.width = ScreenUtils.getScreenWidth() / 100 * 80;
        contentText.setLayoutParams(contentParams);
        contentText.setText(content);
        contentText.setGravity(Gravity.CENTER);
        contentText.setTextColor(getResources().getColor(R.color.mapview_popup_title_color));
        //public
        int left = ScreenUtils.dp2px(this, 15);
        int top = ScreenUtils.dp2px(this, 8);
        int right = ScreenUtils.dp2px(this, 15);
        int bottom = ScreenUtils.dp2px(this, 8);
        titleText.setPadding(left, top, right, bottom);
        contentText.setPadding(left, top, right, bottom);

        linearLayout.addView(titleText);
        linearLayout.addView(contentText);

        LatLng latLng = mMarker.getPosition();
        InfoWindow infoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(linearLayout),
                latLng, -127, listener);
        mBaiduMap.showInfoWindow(infoWindow);
    }

    @Override
    public void onComplete() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded(ResultQueryWorkNet datas) {
        if (datas != null) {
            if (mBaiduMap != null) {
                mBaiduMap.clear();
                LatLng latLng = new LatLng(datas.getLnglaty(), datas.getLnglatx());
                navigateTo(latLng);
                Marker marker = addMarks(datas.getLnglaty(), datas.getLnglatx(), 1, 0 + "", null);
                if (marker != null) {
                    addMarkPopupView(marker, datas.getPointName(), datas.getPointAddress(), datas.getLnglaty(), datas.getLnglatx(), null);
                }
            }
        }
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mBinding.bmapView.onDestroy();
        mPresenter.unbind();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mBinding.bmapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mBinding.bmapView.onPause();
    }

    private void navigateTo(LatLng latLng) {
        MapStatusUpdate mapStatusUpdate1 = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(mapStatusUpdate1);
    }

    //===================定位=====================

    private void initEvent() {
        RxView.clicks(mBinding.btnLocation)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startLocation();
                    }
                });
    }

    public LocationClient mLocationClient = null;

    private void startLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation != null) {
                    mPresenter.loadDatas(bdLocation.getLatitude(), bdLocation.getLongitude());
                } else {
                    Logger.e("locaiton get faild");
                }
            }
        });
        mLocationClient.start();
    }

}
